<form class="layui-form detail_form form-table-edit" action="" lay-filter="template_model-edit-form">

    #if(detail.template_id != null)
    <input type="hidden" name="template_id" value="#(detail.template_id)">
    #end


    <div class="layui-form-item">
        <label class="layui-form-label">模板名称</label>
        <div class="layui-input-block">
            <input type="text" name="template_name" value="#(detail.template_name)" lay-verify="required" placeholder="请输入模板名称" class="layui-input" autocomplete="off">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">需要表数</label>
        <div class="layui-input-block">
            <input type="number" name="table_require_count" value="#(detail.table_require_count)" lay-verify="required" placeholder="请输入需要表数" class="layui-input" autocomplete="off">
        </div>
    </div>


    <div class="layui-form-item">
        <label class="layui-form-label">模板参数</label>
        <div class="layui-input-block">
            <!-- 列表表格 -->
            <table id="param_config_table" lay-filter="param_config_table" style="width: 100%"></table>
            <!-- 显示名称 -->
            <script type="text/html" id="param_title">
                <input type="text" name="param_title_{{d.no}}" value="{{d.title?d.title:''}}" required lay-verify="required" placeholder="显示名称" autocomplete="off" class="layui-input">
            </script>
            <script type="text/html" id="param_name">
                <input type="text" name="param_name_{{d.no}}" value="{{d.name?d.name:''}}" required lay-verify="required" placeholder="显示名称" autocomplete="off" class="layui-input">
            </script>
            <script type="text/html" id="param_value">
                <input type="text" name="param_value_{{d.no}}" value="{{d.value?d.value:''}}" required placeholder="值" autocomplete="off" class="layui-input">
            </script>
            <script type="text/html" id="param_desc">
                <input type="text" name="param_desc_{{d.no}}" value="{{d.desc?d.desc:''}}" required lay-verify="required" placeholder="描述" autocomplete="off" class="layui-input">
            </script>
            <script type="text/html" id="param_oper">
                <a class="layui-btn layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-add-1"></i>添加</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
            </script>
            <!--            <input type="text" name="template_config" value="#(detail.template_config)" lay-verify="required" placeholder="请输入模板配置" class="layui-input" autocomplete="off">-->
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">模板预览图</label>
        <div class="layui-input-block">
            <input type="text" name="thumb" id="temp_thumb" value="#(detail.thumb)" lay-verify="" placeholder="请输入模板编号" class="layui-input" autocomplete="off">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">模板描述</label>
        <div class="layui-input-block">
            <script type="text/plain" style="width:100%;height:800px;border-radius:2px;box-sizing: border-box;border: 1px solid #E6E6E6;" name="desc" id="template_desc">#(detail.desc)</script>
        </div>
    </div>

    <div class="detail_form_footer">
        <a class="layui-btn" lay-submit lay-filter="btn-template_model-submit">保存</a>
        <a class="layui-btn layui-btn-primary" lay-filter="btn-template_model-cancle">取消</a>
    </div>
</form>

<script>
    layui.use(['admin', 'form', 'laydate', 'formSelects', 'xFile', 'xEditor'], function () {
        var $ = layui.$
            , admin = layui.admin
            , element = layui.element
            , layer = layui.layer
            , laydate = layui.laydate
            , table = layui.table
            , formSelects = layui.formSelects
            , xFile = layui.xFile
            , xEditor = layui.xEditor
            , form = layui.form;

        form.render(null, 'template_model-edit-form');

        let thumb = #(notBlank(detail.thumb) ? detail.thumb : '[]');
        xFile.render({
            id: 'temp_thumb',
            base: '/assets/layuiadmin/start/layui/lay/modules/xFile/',
            url: '/file/upload',
            accept: 'images',
            cropImages: false,
            multiple: true,
            rewriteFormValue: function (values) {
                console.log(values, 'values')
                thumb = JSON.stringify(values);
            },
            initValues: thumb,
        });

        xEditor.render({
            id: 'template_desc',
            zIndex: 298910123, //在layui  zindex越大 代表层级 越高
            imageUploadUrl: '/file/upload',
            autoHeightEnabled: false,
            autoFloatEnabled: false,
        });

        /* 自定义验证规则 */
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            }
            , pass: [/(.+){6,12}$/, '密码必须6到12位']
            , content: function (value) {
                layedit.sync(editIndex);
            }
        });

        /* 监听提交 */
        form.on('submit(btn-template_model-submit)', function (data) {
            layer.msg('正在保存中，请稍候', {icon: 16});
            let formVals = data.field;
            formVals.template_config = JSON.stringify(getParamList());
            formVals.thumb = thumb;
            $.ajax({
                method: 'post',
                url: "/generator/template/save",
                data: formVals,
                dataType: 'json',
                success: function (rs) {
                    if (rs.success) {
                        layer.msg(rs.message || '保存成功', {icon: 6});
                        let config = #(detail.template_id == null ? '{page: {curr: 1}}' : '{}');
                        layui.renderTemplateList();
                        layer.closeAll('page'); //关闭所有页面层
                    } else {
                        layer.msg('保存失败,' + rs.message || '保存失败', {icon: 5});
                    }
                },
                error: function (a, b, c) {
                    layer.msg('请求异常，保存失败', {icon: 5});
                }
            });
            return false;
        });
        /* 监听取消 */
        $("[lay-filter=btn-template_model-cancle]").click(function () {
            layer.closeAll("page");
        });
        //枚举表格列定义
        let paramTableCols = [[
            {field: 'title', width: 200, align: 'center', title: '参数标题', event: 'title', templet: "#param_title"},
            {field: 'name', width: 200, align: 'center', title: '参数名', event: 'name', templet: "#param_name"},
            {field: 'value', width: 200, align: 'center', title: '默认值', event: 'value', templet: "#param_value"},
            {field: 'desc', align: 'center', title: '描述', event: 'desc', templet: "#param_desc"},
            {title: '<a class="layui-btn layui-btn-xs" id="temp_param_oper_add"><i class="layui-icon layui-icon-add-1"></i>添加</a>', fixed: 'right', width: 150, templet: '#param_oper'}
        ]]

        // 初始化模板配置参数
        #if(detail.template_config)
        renderParamConfigTable(#(detail.template_config));
        #else
        renderParamConfigTable();
        #end

        function renderParamConfigTable(data) {
            if (!data) {
                data = []
            }
            // 重新设置排序号
            data.forEach((item, idx) => item.no = idx + 1);
            table.render({
                id: "param_config_table",
                elem: '#param_config_table',
                data: data,
                cols: paramTableCols,
                limit: 999,
            })
            // 监听表格行事件
            table.on("tool(param_config_table)", tableEventListener);
        }

        // 添加表格数据
        function addTableData(tableData, preData) {
            let newTableData = [];
            let isAdd = false;
            for (let i = 0; i < tableData.length; i++) {
                newTableData.push(tableData[i]);
                if (preData != null) {
                    if (preData.no == tableData[i].no) {
                        newTableData.push({})
                        isAdd = true;
                    }
                }
            }
            if (!isAdd) {
                newTableData.push({})
            }
            return newTableData;
        }

        // 删除表格数据
        function removeTableData(tableData, data) {
            let newTableData = [];
            for (let i = 0; i < tableData.length; i++) {
                if (data != null) {
                    if (data.no == tableData[i].no) {
                        continue;
                    }
                }
                newTableData.push(tableData[i]);
            }
            return newTableData;
        }


        // 事件监听
        function tableEventListener(obj) {
            let event = obj.event;
            let data = obj.data;
            switch (event) {
                case 'add':
                    renderParamConfigTable(addTableData(getParamList(), data));
                    break;
                case 'del':
                    renderParamConfigTable(removeTableData(getParamList(), data));
                    break;
            }
        }

        let operAddFunc = function () {
            renderParamConfigTable(addTableData(getParamList()));
            $("#temp_param_oper_add").click(operAddFunc);
        };

        $("#temp_param_oper_add").click(operAddFunc)

        function getParamList() {
            let formVals = form.val("template_model-edit-form");
            let enumList = [];
            Object.keys(formVals).forEach(function (key) {
                if (key.indexOf("param_title_") >= 0) {
                    let no = key.substring(12);
                    enumList.push({
                        title: formVals[key],
                        name: formVals["param_name_" + no],
                        value: formVals["param_value_" + no],
                        desc: formVals["param_desc_" + no],
                        no: no,
                    })
                }
            })
            enumList = enumList.sort(function (a, b) {
                return a.no - b.no
            })
            return enumList;
        }

    });
</script>